/**
 * Created by admin on 2017/9/22.
 */
define([
    "helpers/network"
], function (Network) {
    var statusOptions = [{id: "disabled", value: "已禁用"}, {id: "enabled", value: "已启用"}];

    function genStatusSelector(viewId, defaultValue, options) {
        return {
            id: viewId, name: viewId, view: "select", label: "状态",
            value: defaultValue || "",
            options: options || statusOptions
        }
    }

    function genSubmitButton(onClick) {
        return {
            padding: 5,
            cols: [
                {},
                {
                    view: "button", label: "提交", width: 90,
                    click: function () {
                        if (onClick) onClick()
                    }
                }
            ]
        }
    }

    function genMultiSubmitButton(obj) {
        var aaa = [{}];
        _.forEach(obj, function (each) {
            aaa.push(
                {
                    view: "button", label: each.label, width: 90,
                    click: function () {
                        if (each.onclick) each.onclick()
                    }
                })
        });
        return {
            padding: 5,
            cols: aaa
        }
    }


    function genSaveButton() {

    }


    function genSingleImgUploader(viewId, label, defaultValue, required) {
        var webixId_single = webix.uid();
        return {
            rows: [
                {
                    cols: [
                        {
                            id: viewId, name: viewId,
                            view: "text", label: label, required: required, readonly: true, value: defaultValue || ""
                        },
                        {
                            view: "uploader", width: 85,
                            type: "form", value: "选择文件",
                            accept:"image/png, image/jpg, image/jpeg",
                            // id: "mainUploadFile",
                            multiple: false, autosend: false,
                            datatype: "form-data", inputName: "file",
                            formData: {
                                group: "pic"
                            },
                            upload: Network.url.imgUploadUrl + "/file/upload.do",
                            on: {
                                onAfterFileAdd: function (item) {
                                    if(item.size/1048576 > 7){
                                        return;
                                    }
                                    this.send(item.id);
                                },
                                onBeforeFileAdd: function (upload) {
                                    var prevDiv = document.getElementById(webixId_single);
                                    if (upload.file) {
                                        var reader = new FileReader();
                                        if(upload.file.size/1048576 > 7){
                                            webix.message("上传的图片请不要超过7M");
                                            return;
                                        }
                                        reader.onload = function (evt) {
                                            prevDiv.innerHTML = '<img style="width:140px; height:140px" src="' + evt.target.result + '"></img>';
                                        };
                                        reader.readAsDataURL(upload.file);
                                    }
                                },
                                onFileUpload: function (item, response) {
                                    $$(viewId).setValue(response.url);
                                }
                            }
                        }
                    ]
                },
                {
                    height: 160, view: "myFormTemplate",
                    template: function () {
                        if (defaultValue) {
                            return '<div id="' + webixId_single + '"><img style="width:140px; height:140px" src="' + Network.url.imgUrl + defaultValue + '" /></div>'
                        }
                        return '<div id="' + webixId_single + '"></div>'
                    }
                }
            ]
        }
    }

    function genMultiImgsUploader(viewId, defaultValue, required) {
        var webixId_multi = webix.uid();
        return {
            rows: [
                {
                    cols: [
                        {
                            id: viewId, name: viewId,
                            view: "text", label: "幻灯图", required: required, readonly: true, value: defaultValue || ""
                        },
                        {
                            view: "uploader", width: 85, type: "form",
                            value: "选择文件", multiple: true, autosend: false,
                            datatype: "form-data", inputName: "file",
                            formData: {
                                group: "slides"
                            },
                            upload: Network.url.imgUploadUrl + "/file/upload.do",
                            on: {
                                onAfterFileAdd: function (item) {
                                    this.send(item.id);
                                },
                                onFileUpload: function (item, res) {
                                    if (res) {
                                        $$(viewId).setValue(res.url + ($$(viewId).getValue() ? ";" : "") + $$(viewId).getValue());
                                        var prevDiv = document.getElementById(webixId_multi);
                                        var slideImgs = '<div style="float: left"><img style="width:140px; height:140px; margin: 0 10px" src="' + Network.url.imgUrl + res.url + '" /><p onclick="this.parentNode.remove()" id="deleteImg" style="color: red; text-align: center; cursor:pointer">x 删除</p></div>'
                                        var slideImgs = '<div style="float: left">' +
                                            '<img style="width:140px; height:140px; margin: 0 10px" src="' + Network.url.imgUrl + res.url + '" />' +
                                            '<p onclick="var imgPath = this.parentNode.firstChild.src.split(\'' + Network.url.imgUrl + '\')[1];var newVal = $$(\'' + viewId + '\').getValue().split(\';\').filter(function(each){return each != imgPath});$$(\'' + viewId + '\').setValue(newVal.join(\';\'));this.parentNode.remove()" id="deleteImg" style="color: red; text-align: center; cursor:pointer">x 删除</p></div>';
                                        prevDiv.insertAdjacentHTML('beforeend', slideImgs)
                                    } else {
                                        webix.message("请重新上传")
                                    }
                                }
                            }
                        }
                    ]
                },
                {
                    height: 200,
                    // view:"template",
                    template: function () {
                        if (defaultValue) {
                            var albumHtml = "";
                            _.forEach(defaultValue, function (each) {
                                albumHtml += '<div style="float: left">' +
                                    '<img style="width:140px; height:140px; margin: 0 10px" src="' + Network.url.imgUrl + each + '" />' +
                                    '<p onclick="var imgPath = this.parentNode.firstChild.src.split(\'' + Network.url.imgUrl + '\')[1];var newVal = $$(\'' + viewId + '\').getValue().split(\';\').filter(function(each){return each != imgPath});$$(\'' + viewId + '\').setValue(newVal.join(\';\'));this.parentNode.remove()" id="deleteImg" style="color: red; text-align: center; cursor:pointer">x 删除</p>' +
                                    '</div>'
                            });
                            return '<div id="' + webixId_multi + '">' + albumHtml + '</div>'
                        }
                        return '<div id="' + webixId_multi + '"></div>'
                    }
                }
            ]
        }
    }

    function genSingleOptionSelector(viewId, label, data, defaultValue, required,labelWidth) {
        return {
            id: viewId, name: viewId, view: "combo", label: label, placeholder: "请选择" + label,
            required: required, labelWidth: labelWidth ? labelWidth : 80, value: defaultValue ? defaultValue : "",
            // validate: required ? webix.rules.isNotEmpty : undefined ,
            options: {
                data: data,
                filter: function (item, value) {
                    if (item.value.toString().toLowerCase().indexOf(value.toLowerCase()) !== -1) {
                        return true;
                    }
                }
            }
        }
    }

    function genKeywordsSelector(viewId, data, defValue) {
        return {
            id: viewId, name: viewId, view: "select", width: 100, css: {"text-align": "center"},
            value: defValue || data[0].id,
            options: data
        }
    }

    function genKeywordsUI(viewId, placeholder, onKeyPress) {
        return {
            id: viewId, name: viewId, view: "text", width: 300, placeholder: placeholder,
            on: {
                onKeyPress: function (code) {
                    if (code !== 13) {
                        return
                    }
                    if (onKeyPress) {
                        onKeyPress()
                    }
                }
            }
        }
    }

    function genQueryButtonUI(func) {
        return {
            view: "button", label: "检索", width: 90, type: "form", click: function () {
                func()
            }
        }
    }

    // function genQueryButtonBUY(func) {
    //     return {
    //         view: "button", label: "买单排行", width: 90, type: "form", click: function () {
    //             func()
    //         }
    //     }
    // }
    //
    // function genQueryButtonSELL(func) {
    //     return {
    //         view: "button", label: "售单排行", width: 90, type: "form", click: function () {
    //             func()
    //         }
    //     }
    // }

    function genMultiOptionsSelector(id, label, data, defaultValue,required, labelAlign) {
        // if (!defaultValue) {
        //     defaultValue = [];
        //     _.forEach(data, function (each) {
        //         defaultValue.push(each.id)
        //     });
        //     defaultValue = defaultValue.join(",")
        // }
        return {
            id: id,
            view: "multiselect", name: id, label: label, width: 200, labelAlign: labelAlign || "right",
            required: required || false ,
            // value: defaultValue || data,
            value: defaultValue,
            options: data
        }
    }

    function genDateRageSelectorUI(id, label, defaultVal) {
        var ret = {
            id: id,
            view: "daterangepicker", name: id, width: 280, label: label, labelAlign: "right",
            labelWidth: 100
        };
        if (defaultVal) {
            ret.value = {};
            ret.value.start = defaultVal.start || Date.getDate();
            ret.value.start = defaultVal.end || Date.getDate();
        }
        return ret
    }

    function genPopupPictureUI(picUrl, thumbnailWidth, popUpWidth) {
        var uid = webix.uid();
        return {
            view: "template", autoheight: true, align: "center",
            borderless: true, css: {"margin-top": "0 !important"},
            onClick: {
                "showPic": function (e, id, trg) {
                    document.getElementById(uid).style.display = "block";
                    console.log(e, id, trg)
                },
                "hidePic": function () {
                    document.getElementById(uid).style.display = "none";
                },
                "zoomIn": function () {
                    var imgEle = document.getElementById(uid).getElementsByTagName("img")[0];
                    imgEle.width = imgEle.width - 50;
                },
                "zoomOut": function () {
                    var imgEle = document.getElementById(uid).getElementsByTagName("img")[0];
                    imgEle.width = imgEle.width + 50;
                },
                "rotatePic": function (e, id, trg) {
                    var element = document.getElementById(uid);
                    if (element.attributes["img-orientation"].value == "0") {
                        element.childNodes[1].style.transform = "rotate(" + 90 + "deg)";
                        element.attributes["img-orientation"].value = "1";
                    } else if (element.attributes["img-orientation"].value == "1") {
                        element.childNodes[1].style.transform = "rotate(" + 180 + "deg)";
                        element.attributes["img-orientation"].value = "2";
                    } else if (element.attributes["img-orientation"].value == "2") {
                        element.childNodes[1].style.transform = "rotate(" + 270 + "deg)";
                        element.attributes["img-orientation"].value = "3";
                    } else if (element.attributes["img-orientation"].value == "3") {
                        element.childNodes[1].style.transform = "rotate(" + 0 + "deg)";
                        element.attributes["img-orientation"].value = "0";
                    }
                    if (element.attributes["img-orientation"].value == "0" || element.attributes["img-orientation"].value == "2") {
                        element.style.width = element.childNodes[1].width + "px";
                        element.style.height = element.childNodes[1].height + "px";
                        element.childNodes[1].style.marginLeft = "0";
                        element.childNodes[1].style.marginTop = "0";
                    } else {
                        element.style.width = element.childNodes[1].height + "px";
                        element.style.height = element.childNodes[1].width + "px";
                        element.childNodes[1].style.marginLeft = (element.childNodes[1].height - element.childNodes[1].width) / 2 + "px";
                        element.childNodes[1].style.marginTop = (element.childNodes[1].width - element.childNodes[1].height) / 2 + "px";
                    }
                }
            },
            template: function () {
                // return "<div class='showPic'>"+each+"<img src="+Network.url.imgUrl+"'assets/imgs/logo.png'></div>"
                return "<div style='text-align:center'><img  class='showPic' src='" + Network.url.imgUrl + picUrl + "' width='" + thumbnailWidth + "px' height='" + thumbnailWidth + "px'>" +
                    "<div id='" + uid + "' class='picContainer' img-orientation='0' style='width: auto;height: auto'>" +
                    "<div class='pic-operation'>" +
                    "<div class='hidePic fa fa-close'></div><div class='rotatePic fa fa-rotate-right'></div><div class='zoomIn fa fa-minus'></div><div class='zoomOut fa fa-plus'></div>" +
                    "</div>" +
                    "<img style='border: 2px solid;' src='" + Network.url.imgUrl + picUrl + "' width=" + popUpWidth + "></div>" +
                    "</div>"
            }
        }
    }

    return {
        statusOptions: statusOptions,
        genKeywordsSelector: genKeywordsSelector,
        genKeywordsUI: genKeywordsUI,
        genDateRageSelectorUI: genDateRageSelectorUI,
        genStatusSelector: genStatusSelector,

        genSubmitButton: genSubmitButton,
        genMultiSubmitButton: genMultiSubmitButton,
        genSaveButton: genSaveButton,

        genSingleImgUploader: genSingleImgUploader,
        genMultiImgsUploader: genMultiImgsUploader,

        genSingleOptionSelector: genSingleOptionSelector,
        genMultiOptionsSelector: genMultiOptionsSelector,

        genQueryButtonUI: genQueryButtonUI,
        // genQueryButtonBUY: genQueryButtonBUY,
        // genQueryButtonSELL: genQueryButtonSELL,
        genPopupPictureUI: genPopupPictureUI
    }
});